<script setup>
import {ref, onMounted, watch, computed} from 'vue';
import {
  ElButton,
  ElTable,
  ElTableColumn,
  ElMessage,
  ElDialog,
  ElForm,
  ElInput,
  ElSelect,
  ElOption,
  ElPagination, ElMessageBox
} from 'element-plus';
import {
  GetAdUnits,
  AddAdUnit,
  RemoveUnit,
  UpdateUnit,
  ActivateAdUnit,
  DeactivateAdUnit,
  GetAdPlans,
  GetAdCreatives,
  AddCreativeToAdUnit,
  RemoveCreativeFromAdUnit,
  GetAdUnitCreatives
} from '@/api/index.js'; // 假设你有获取所有广告单元的接口
import useUserInfoStore from '@/store/user.js';


const userStore = useUserInfoStore();
const adUnits = ref([]);  // 用于存储广告单元数据


const totalItems = ref(0); // 总条目数
const currentPage = ref(1); // 当前页
const pageSize = ref(10); // 每页条目数
const sortField = ref('');
const handlePageChange = (page) => {
  currentPage.value = page;
  getAdUnits();
};
// 处理排序字段变化
const handleSortChange = () => {
  getAdUnits();
};


const currentAdPlan = ref({}); // 当前选择的广告计划
const isAdUnitFormVisible = ref(false);  // 用于显示广告单元添加表单
const newAdUnit = ref({
  unit_name: '',
  position_type: 0,
  budget_fee: 0,
  plan_id: ''
});

// 获取所有广告单元列表
const getAdUnits = async () => {
  try {
    const response = await GetAdUnits({
          page: currentPage.value,
          page_size: pageSize.value,
          order_by: sortField.value, // 传递排序字段
          search: searchText.value, // 传递搜索关键词
        }
    );  // 使用API获取所有广告单元
    adUnits.value = response.results; // 将获取的广告单元数据存储到 adUnits
    totalItems.value = response.count; // 更新总条目数
  } catch (error) {
    ElMessage.error('无法加载广告单元，请稍后重试');
  }
};


// 打开广告单元添加表单
const toggleAdUnitForm = () => {
  isAdUnitFormVisible.value = true;
  // 清空表单数据
  newAdUnit.value = {
    unit_name: '',
    position_type: 0,
    budget_fee: 0,
  };
};

// 创建广告单元
const createAdUnit = async () => {
  if (!newAdUnit.value.unit_name || !newAdUnit.value.budget_fee) {
    ElMessage.error('请填写所有必填字段');
    return;
  }

  try {
    await AddAdUnit({
      plan_id: currentAdPlan.value.id,  // 将广告计划 ID 与新广告单元关联
      ...newAdUnit.value,
    });

    // 成功后刷新广告单元列表
    await getAdUnits();  // 刷新所有广告单元
    ElMessage.success('广告单元添加成功');
    isAdUnitFormVisible.value = false;
  } catch (error) {
    ElMessage.error('添加广告单元失败，请稍后再试');
  }
};

const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const getPositionTypeLabel = (type) => {
  switch (type) {
    case 0:
      return '开屏';
    case 1:
      return '贴片';
    case 2:
      return '中贴';
    case 3:
      return '暂停贴';
    case 4:
      return '后贴';
    default:
      return '未知';
  }
};

const deleteAdUnit = (id) => {
  ElMessageBox.confirm(
      '确定删除此广告单元吗?',
      '删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }
  ).then(async () => {
    try {
      await RemoveUnit(id);
      adUnits.value = adUnits.value.filter(item => item.id !== id);
      totalItems.value--;
      await getAdUnits();
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('网络错误，请稍后尝试删除！')
    }
  })
}
const currentUnit = ref({})
const isEditDialogVisible = ref(false);
const editAdUnit = (id) => {

  const unit = adUnits.value.find(item => item.unit_id === id);
  if (unit) {
    currentUnit.value = {...unit};
    // 打开编辑对话框
    isEditDialogVisible.value = true;
  } else {
    ElMessage.error('未找到对应的广告计划');
  }
}
const newHobby = ref('')
const newProvince = ref('')
const newCity = ref('')

const addHobby = () => {
  if (newHobby.value.trim()) {
    if (!currentUnit.value.hobbies) {
      currentUnit.value.hobbies = []
    }
    currentUnit.value.hobbies.push({
      id: Date.now(), // 临时ID
      hobby_tag: newHobby.value.trim()
    })
    newHobby.value = ''
  }
}

const removeHobby = (index) => {
  currentUnit.value.hobbies.splice(index, 1)
}

const addDistrict = () => {
  if (newProvince.value.trim()) {
    if (!currentUnit.value.districts) {
      currentUnit.value.districts = []
    }
    currentUnit.value.districts.push({
      id: Date.now(), // 临时ID
      province: newProvince.value.trim(),
      city: newCity.value.trim() || ''
    })
    newProvince.value = ''
    newCity.value = ''
  }
}

const removeDistrict = (index) => {
  currentUnit.value.districts.splice(index, 1)
}
const updateUnit = async () => {
  if (!currentUnit.value.unit_name || !currentUnit.value.budget_fee) {
    ElMessage.error('请填写所有必填字段');
    return;
  }

  try {
    await UpdateUnit(currentUnit.value.unit_id, {
      unit_name: currentUnit.value.unit_name,
      budget_fee: currentUnit.value.budget_fee,
      position_type: currentUnit.value.position_type,
      hobbies: currentUnit.value.hobbies,
      districts: currentUnit.value.districts
    });
    ElMessage.success('广告计划更新成功');
    await getAdUnits();
    // 关闭编辑对话框
    isEditDialogVisible.value = false;
  } catch (error) {
    // 出现错误时，显示错误提示
    ElMessage.error('更新广告计划失败，请稍后再试');
  }
};
const activateAdUnit = (id) => {
  ElMessageBox.confirm(
      '确定启用此广告单元吗?',
      '启用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }
  ).then(
      async () => {
        try {
          await ActivateAdUnit(id);
          // 更新当前行的状态
          const unit = adUnits.value.find(item => item.unit_id === id);
          if (unit) {
            unit.unit_status = 1;  // 设置状态为已激活
          }
          ElMessage.success('广告单元已启用');
        } catch (error) {
          ElMessage.error('网络错误，请稍后尝试！')
        }
      }
  )
}
const deactivateAdUnit = (id) => {
  ElMessageBox.confirm(
      '确定停用此广告单元吗?',
      '停用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }
  ).then(
      async () => {
        try {
          await DeactivateAdUnit(id);
          // 更新当前行的状态
          const unit = adUnits.value.find(item => item.unit_id === id);
          if (unit) {
            unit.unit_status = 0;  // 设置状态为未激活
          }
          ElMessage.warning('广告计划已停用');
        } catch (error) {
          ElMessage.error('网络错误，请稍后尝试！')
        }
      }
  )
}


// 获取广告计划列表
const adPlans = ref([]); // 广告计划列表d
const getAdPlans = async () => {
  try {
    const response = await GetAdPlans({
      page: currentPage.value,
      page_size: pageSize.value,
      order_by: sortField.value, // 传递排序字段
    });
    adPlans.value = response.results;
    totalItems.value = response.count; // 更新总条目数
  } catch (error) {
    console.error('Error fetching ad plans:', error);
  }
};
const searchText = ref(''); // 搜索关键词
// 处理搜索
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置到第一页
  getAdUnits();
};
// 监听搜索关键词的变化，添加防抖
let searchTimeout = null;
watch(searchText, () => {
  clearTimeout(searchTimeout);
  searchTimeout = setTimeout(() => {
    handleSearch();
  }, 300); // 300ms 防抖
});


// 页面加载时获取所有广告单元
onMounted(() => {
  getAdUnits();
  getAdPlans();
});
const isAddCreativeDialogVisible = ref(false);
const isRemoveCreativeDialogVisible = ref(false);
const currentAdUnitId = ref(null);
const allCreatives = ref([]); // 所有创意列表
const creativePage = ref(1); // 当前页码
const creativePageSize = ref(10); // 每页条数
const creativeTotal = ref(0); // 创意总数


const selectedCreatives = ref([]); // 用于存储用户选中的创意
const handleSelectionChange = (selection) => {
  selectedCreatives.value = selection; // 更新选中的创意
};
// 打开添加创意对话框
const openAddCreativeDialog = async (adUnitId) => {
  currentAdUnitId.value = adUnitId;
  try {
    await loadCreatives(); // 加载创意列表
    selectedCreatives.value = []; // 清空选中的创意
    isAddCreativeDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取创意列表失败，请稍后再试');
  }
};
const loadCreatives = async () => {
  try {
    // 获取当前广告单元已经绑定的创意
    const response = await GetAdUnitCreatives(currentAdUnitId.value);
    const boundCreatives = response.map(creative => creative.creative_id);
    // 获取所有创意
    const allCreativesResponse = await GetAdCreatives({
      page: creativePage.value,
      page_size: creativePageSize.value,
      search: creativeSearchText.value,
    });

    // 过滤掉已经绑定的创意
    allCreatives.value = allCreativesResponse.results.filter(
        creative => !boundCreatives.includes(creative.creative_id)
    );
    creativeTotal.value = allCreativesResponse.count;
  } catch (error) {
    ElMessage.error('加载创意列表失败，请稍后再试');
  }
};
const creativeSearchText = ref(''); // 搜索关键词
// 过滤后的创意列表
const filteredCreatives = computed(() => {
  if (!creativeSearchText.value) {
    return allCreatives.value; // 如果没有搜索关键词，返回全部创意
  }
  return allCreatives.value.filter(creative =>
      creative.name.toLowerCase().includes(creativeSearchText.value.toLowerCase())
  );
});

const handleCreativeSearch = async () => {
  creativePage.value = 1;
  try {
    const response = await GetAdCreatives({
      page: creativePage.value,
      page_size: creativePageSize.value,
      search: creativeSearchText.value, // 传递搜索关键词
    });
    allCreatives.value = response.results;
    creativeTotal.value = response.count;
  } catch (error) {
    ElMessage.error('搜索创意失败，请稍后再试');
  }
};
// 处理分页变化
const handleCreativePageChange = (page) => {
  creativePage.value = page;
  loadCreatives(); // 重新加载创意列表
};

// 添加创意
const addCreative = async () => {
  if (selectedCreatives.value.length === 0) {
    ElMessage.error('请选择至少一个创意');
    return;
  }
  try {
    for (const creative of selectedCreatives.value) {
      await AddCreativeToAdUnit({
        ad_unit_id: currentAdUnitId.value,
        creative_id: creative.creative_id,
      });
    }
    ElMessage.success('创意添加成功');
    isAddCreativeDialogVisible.value = false;
    selectedCreatives.value = []; // 清空选中的创意
  } catch (error) {
    ElMessage.error('添加创意失败，请稍后再试');
  }
};


const adUnitCreatives = ref([]); // 当前广告单元绑定的创意列表
const selectedCreativesToRemove = ref([]); // 用于存储用户选中的创意
const handleRemoveSelectionChange = (selection) => {
  selectedCreativesToRemove.value = selection;
};
// 打开删除创意对话框
const openRemoveCreativeDialog = async (adUnitId) => {
  currentAdUnitId.value = adUnitId;
  try {
    const response = await GetAdUnitCreatives(adUnitId); // 获取当前广告单元绑定的创意
    adUnitCreatives.value = response;
    isRemoveCreativeDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取创意列表失败，请稍后再试');
  }
};

// 删除创意
const removeCreative = async () => {
  if (selectedCreativesToRemove.value.length === 0) {
    ElMessage.error('请选择至少一个创意');
    return;
  }
  try {
    for (const creative of selectedCreativesToRemove.value) {
      await RemoveCreativeFromAdUnit({
        ad_unit_id: currentAdUnitId.value,
        creative_id: creative.creative_id,
      });
    }
    ElMessage.success('创意删除成功');
    isRemoveCreativeDialogVisible.value = false;
    selectedCreativesToRemove.value = []; // 清空选中的创意
    await openRemoveCreativeDialog(currentAdUnitId.value); // 刷新列表
  } catch (error) {
    ElMessage.error('删除创意失败，请稍后再试');
  }
};

function formatSize(size) {
  return `${(size / 1024).toFixed(2)} KB`
}

function getMaterialType(creativeType) {
  const materialTypes = {
    0: 'BMP',
    1: 'JPG',
    2: 'PNG',
    3: 'MP4',
    4: 'AVI'
  };
  return materialTypes[creativeType] || '未知';
}

function formatDuration(seconds) {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

const formatCurrency = (row, column, cellValue, index) => {
  const value = Number(cellValue).toLocaleString('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  });
  return value;
};

</script>

<template>
  <div class="ad-unit-container">
    <!-- 广告单元列表显示 -->
    <div class="action-bar">
      <el-button @click="toggleAdUnitForm" type="primary">添加广告单元</el-button>
    </div>
    <div class="header">
      <h1>广告单元列表</h1>
      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
            v-model="searchText"
            placeholder="请输入广告单元名称搜索"
            clearable
            @clear="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch" icon="el-icon-search"></el-button>
          </template>
        </el-input>
      </div>
      <!-- 排序选择 -->
      <div class="sort-container">
        <el-select v-model="sortField" placeholder="排序" @change="handleSortChange">
          <el-option label="广告单元名称" value="unit_name"></el-option>
          <el-option label="预算" value="budget_fee"></el-option>
          <el-option label="状态" value="unit_status"></el-option>
          <el-option label="广告位类型" value="position_type"></el-option>
          <el-option label="广告计划" value="ad_plan_name"></el-option>
          <el-option label="创建时间" value="create_time"></el-option>
        </el-select>
      </div>

    </div>

    <!-- 表格展示广告单元列表 -->
    <el-table :data="adUnits" style="width: 100%" stripe>
      <el-table-column label="广告单元名称" prop="unit_name"></el-table-column>
      <el-table-column label="预算" prop="budget_fee" width="100px" :formatter="formatCurrency"></el-table-column>
      <el-table-column label="状态" prop="unit_status" align="center">
        <template #default="{ row }">
          <span>{{ row.unit_status === 1 ? '已启用' : '未启用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="广告位类型" prop="position_type">
        <template #default="{ row }">
          <span>{{ getPositionTypeLabel(row.position_type) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划名称" prop="plan_name"></el-table-column>
      <el-table-column label="创建时间" prop="create_time">
        <template #default="{ row }">
          <span>{{ formatDate(row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="兴趣标签" width="120px">
        <template #default="{ row }">
          <el-tag
              v-for="hobby in row.hobbies"
              :key="hobby.id"
              type="primary"
              style="margin-right: 5px;"
          >
            {{ hobby.hobby_tag }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="地域标签" width="150px">
        <template #default="{ row }">
          <el-tag
              v-for="district in row.districts"
              :key="district.id"
              type="success"
              style="margin-right: 5px;"
          >
            {{ district.province }}{{ district.city ? ' - ' + district.city : '' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200px">
        <template #default="{ row }">
          <el-button-group>
            <el-button @click="editAdUnit(row.unit_id)" type="primary" size="small">编辑</el-button>
            <el-button @click="deleteAdUnit(row.unit_id)" type="danger" size="small">删除</el-button>
            <!-- 添加创意按钮 -->
            <el-button @click="openAddCreativeDialog(row.unit_id)" type="success" size="small">添加创意</el-button>
            <!-- 删除创意按钮 -->
            <el-button @click="openRemoveCreativeDialog(row.unit_id)" type="warning" size="small">删除创意</el-button>
            <!-- 启用(停用)按钮仅管理员可见 -->
            <el-button
                v-if="userStore.userInfo.status === 1 && row.unit_status === 0"
                @click="activateAdUnit(row.unit_id)"
                type="success"
                size="small"
            >
              启用
            </el-button>
            <el-button
                v-if="userStore.userInfo.status === 1 && row.unit_status === 1"
                @click="deactivateAdUnit(row.unit_id)"
                type="warning"
                size="small"
            >
              停用
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页控件 -->
    <el-pagination
        v-if="totalItems > 0"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalItems"
        @current-change="handlePageChange"
        layout="total, prev, pager, next, jumper"
        class="custom-pagination"
    ></el-pagination>
    <!-- 添加广告单元的表单 -->
    <el-dialog v-model="isAdUnitFormVisible" title="添加广告单元">
      <el-form :model="newAdUnit" ref="createAdUnitForm" label-width="80px">
        <el-form-item label="广告单元名称">
          <el-input v-model="newAdUnit.unit_name"></el-input>
        </el-form-item>
        <el-form-item label="广告位类型">
          <el-select v-model="newAdUnit.position_type" placeholder="请选择类型">
            <el-option label="开屏" :value="0"></el-option>
            <el-option label="贴片" :value="1"></el-option>
            <el-option label="中贴" :value="2"></el-option>
            <el-option label="暂停贴" :value="3"></el-option>
            <el-option label="后贴" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预算">
          <el-input v-model="newAdUnit.budget_fee" type="number"></el-input>
        </el-form-item>
        <el-form-item label="广告计划">
          <el-select v-model="newAdUnit.plan_id" placeholder="请选择广告计划">
            <el-option
                v-for="plan in adPlans"
                :key="plan.id"
                :label="plan.name"
                :value="plan.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isAdUnitFormVisible = false">关闭</el-button>
        <el-button type="primary" @click="createAdUnit">添加</el-button>
      </span>
    </el-dialog>
    <!--   编辑广告单元dialog-->
    <el-dialog v-model="isEditDialogVisible" title="编辑广告单元">
      <el-form :model="currentUnit" ref="adPlanForm" label-width="100px">
        <el-form-item label="广告计划名称">
          <el-input v-model="currentUnit.unit_name"></el-input>
        </el-form-item>
        <el-form-item label="预算">
          <el-input v-model="currentUnit.budget_fee"></el-input>
        </el-form-item>
        <el-form-item label="广告位类型">
          <el-select v-model="currentUnit.position_type" placeholder="请选择类型">
            <el-option label="开屏" :value="0"></el-option>
            <el-option label="贴片" :value="1"></el-option>
            <el-option label="中贴" :value="2"></el-option>
            <el-option label="暂停贴" :value="3"></el-option>
            <el-option label="后贴" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-input :value="currentUnit.unit_status === 1 ? '已启用' : '未启用'" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input :value="formatDate(currentUnit.create_time)" disabled></el-input>
        </el-form-item>
        <el-form-item label="兴趣标签">
          <div class="tag-container">
            <el-tag
                v-for="(hobby, index) in currentUnit.hobbies"
                :key="hobby.id"
                type="primary"
                closable
                @close="removeHobby(index)"
                class="custom-tag"
            >
              {{ hobby.hobby_tag }}
            </el-tag>
            <div class="input-group">
              <el-input
                  v-model="newHobby"
                  placeholder="输入新兴趣标签"
                  class="hobby-input"
                  @keyup.enter="addHobby"
              />
              <el-button
                  type="primary"
                  icon="Plus"
                  @click="addHobby"
                  class="add-btn"
              >添加</el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="地域标签">
          <div class="tag-container">
            <el-tag
                v-for="(district, index) in currentUnit.districts"
                :key="district.id"
                type="success"
                closable
                @close="removeDistrict(index)"
                class="custom-tag"
            >
              {{ district.province }}{{ district.city ? ` - ${district.city}` : '' }}
            </el-tag>
            <div class="input-group">
              <el-input
                  v-model="newProvince"
                  placeholder="省份"
                  class="district-input"
              />
              <el-input
                  v-model="newCity"
                  placeholder="城市（可选）"
                  class="district-input"
              />
              <el-button
                  type="primary"
                  icon="Plus"
                  @click="addDistrict"
                  class="add-btn"
              >添加</el-button>
            </div>
          </div>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUnit">更新</el-button>
      </span>
    </el-dialog>

    <el-dialog v-model="isAddCreativeDialogVisible" title="添加创意">
      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
            v-model="creativeSearchText"
            placeholder="请输入创意名称搜索"
            clearable
            @clear="handleCreativeSearch"
            @input="handleCreativeSearch"
        >
          <template #append>
            <el-button @click="handleCreativeSearch" icon="el-icon-search"></el-button>
          </template>
        </el-input>
      </div>

      <!-- 创意列表 -->
      <el-table :data="filteredCreatives" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="创意名称" prop="name"></el-table-column>
        <el-table-column label="创意类型" prop="creative_type">
          <template #default="{ row }">
        <span>
          {{ row.creative_type === 0 ? '图片' : '视频' }}
          <span v-if="row.creative_type === 1">
        ({{ formatDuration(row.duration) }})
          </span>
        </span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" prop="audit_status">
          <template #default="{ row }">
            <span>{{ row.audit_status === 0 ? '已通过' : '未通过' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="物料类型" prop="material_type">
          <template #default="{ row }">
            <span>{{ getMaterialType(row.material_type) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="高度" prop="height"></el-table-column>
        <el-table-column label="宽度" prop="width"></el-table-column>
        <el-table-column label="大小" prop="size">
          <template #default="{ row }">
            <span>{{ formatSize(row.size) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创作者" prop="user_name">
          <template #default="{ row }">
            <span>{{ row.user_name ? row.user_name : '未知创造者' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template #default="{ row }">
            <span>{{ formatDate(row.create_time) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
          v-if="creativeTotal > 0"
          :current-page="creativePage"
          :page-size="creativePageSize"
          :total="creativeTotal"
          @current-change="handleCreativePageChange"
          layout="prev, pager, next"
          class="creative-pagination"
      ></el-pagination>
      <span slot="footer" class="dialog-footer">
    <el-button @click="isAddCreativeDialogVisible = false">关闭</el-button>
    <el-button type="primary" @click="addCreative">添加</el-button>
  </span>
    </el-dialog>
    <el-dialog v-model="isRemoveCreativeDialogVisible" title="删除创意">
      <!-- 创意列表 -->
      <el-table :data="adUnitCreatives" style="width: 100%" @selection-change="handleRemoveSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="创意名称" prop="name"></el-table-column>
        <el-table-column label="创意类型" prop="creative_type">
          <template #default="{ row }">
        <span>
          {{ row.creative_type === 0 ? '图片' : '视频' }}
          <span v-if="row.creative_type === 1">
        ({{ formatDuration(row.duration) }})
          </span>
        </span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" prop="audit_status">
          <template #default="{ row }">
            <span>{{ row.audit_status === 0 ? '已通过' : '未通过' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="物料类型" prop="material_type">
          <template #default="{ row }">
            <span>{{ getMaterialType(row.material_type) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="高度" prop="height"></el-table-column>
        <el-table-column label="宽度" prop="width"></el-table-column>
        <el-table-column label="大小" prop="size">
          <template #default="{ row }">
            <span>{{ formatSize(row.size) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创作者" prop="user_name">
          <template #default="{ row }">
            <span>{{ row.user_name ? row.user_name : '未知创造者' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template #default="{ row }">
            <span>{{ formatDate(row.create_time) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
    <el-button @click="isRemoveCreativeDialogVisible = false">关闭</el-button>
    <el-button type="primary" @click="removeCreative">删除</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .sort-container {
    width: 200px;
  }
}

.el-button-group {
  display: flex;
  gap: 10px; /* 按钮之间的间距 */
  flex-wrap: wrap; /* 如果按钮过多，自动换行 */
}
.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
  padding: 8px;
  border-radius: 4px;
  background: #f8f9fa;

  .custom-tag {
    margin: 2px;
    padding: 0 10px;
    height: 28px;
    line-height: 26px;
    border-radius: 14px;
  }
}

.input-group {
  display: inline-flex;
  gap: 8px;
  align-items: center;
  background: white;
  padding: 4px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);

  .hobby-input {
    width: 150px;

    :deep(.el-input__inner) {
      height: 32px;
      padding: 0 12px;
    }
  }

  .district-input {
    width: 120px;

    :deep(.el-input__inner) {
      height: 32px;
      padding: 0 12px;
    }
  }

  .add-btn {
    padding: 8px 16px;
    height: 32px;
    border-radius: 16px;
  }
}

// 响应式处理
@media (max-width: 768px) {
  .input-group {
    flex-wrap: wrap;

    .district-input {
      width: 100%;
    }

    .add-btn {
      width: 100%;
      margin-top: 8px;
    }
  }
}
</style>